package com.zfl.thread.day03;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@AllArgsConstructor
@NoArgsConstructor
class BankC {
    private volatile int balance = 0;
    private volatile boolean flag = true;
    private static Lock lock = new ReentrantLock();
    private static Condition con_withdarw = lock.newCondition();
    private static Condition con_deposity = lock.newCondition();

    public void withdraw(int money) {
        lock.lock();
        try {
            while (!flag) {
                System.out.println("不可取款，应该存款");
                con_withdarw.await();
            }
            System.out.println("进行取款");
            this.balance -= money;
            flag = !flag;
            System.out.println(Thread.currentThread().getName() + money + "元，余额[" + this.getBalance() + "]元");
            con_deposity.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    public void deposity(int money) {
        lock.lock();
        try {
            while (flag) {
                System.out.println("不可存款，应该取款");
                con_deposity.await();
            }
            System.out.println("进行存款");
            this.balance += money;
            flag = !flag;
            System.out.println(Thread.currentThread().getName() + money + "元，余额[" + this.getBalance() + "]元");
            con_withdarw.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

public class ConditionDemo04 {
    public static void main(String[] args) {
        BankC bankC = new BankC();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                bankC.withdraw(i);
            }
        }, "取款").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                bankC.deposity(i);
                System.out.println(Thread.currentThread().getName() + i + "元，余额[" + bankC.getBalance() + "]元");
            }
        }, "存款").start();
    }
}
